from multiprocessing import AuthenticationError

import jwt
import datetime
from django.conf import settings
from rest_framework.authentication import BasicAuthentication
from rest_framework.exceptions import AuthenticationFailed

header = {
    'alg': 'HS256',
    'typ': 'JWT'
}

SECRET_KEY = settings.SECRET_KEY


class ToolJWT:
    def gettoken(self, user):
        payload = {
            'userid': user.get('id'),
            'username': user.get('username',),
            'exp': datetime.datetime.now() + datetime.timedelta(hours=2)
        }
        token = jwt.encode(payload, SECRET_KEY, algorithm='HS256', headers=header)
        return token

    def checktoken(self, token):
        try:
            payload = jwt.decode(token, SECRET_KEY, algorithms='HS256')
            return payload
        except jwt.ExpiredSignatureError:
            raise AuthenticationFailed('token过期')
        except jwt.InvalidTokenError:
            raise AuthenticationFailed('token无效')


tooljwt = ToolJWT()
# print(tool.gettoken({"id": 1, "username": "admin"}))
